import { Configuration, AuthApi, UsersApi, PermissionsApi } from './generated/src/index';
import { API_CONFIG } from './config';

// Token管理器
export const tokenManager = {
  getToken: (): string | null => localStorage.getItem('access_token'),
  setToken: (token: string): void => localStorage.setItem('access_token', token),
  removeToken: (): void => localStorage.removeItem('access_token'),
  getRefreshToken: (): string | null => localStorage.getItem('refresh_token'),
  setRefreshToken: (token: string): void => localStorage.setItem('refresh_token', token),
};

// 白名单接口（不需要认证）
const isPublicEndpoint = (url: string): boolean => {
  const publicPaths = ['/auth/token/', '/auth/register/', '/health/', '/docs/', '/schema/'];
  return publicPaths.some(path => url.includes(path));
};

// Token刷新处理 - 使用全局配置和生成的API客户端
const handleTokenRefresh = async (): Promise<boolean> => {
  const refreshToken = tokenManager.getRefreshToken();
  if (!refreshToken) return false;

  try {
    // 🔑 关键：使用全局API配置，避免重复的basePath逻辑
    const tempConfig = new Configuration({
      basePath: API_CONFIG.basePath,
    });
    const tempAuthClient = new AuthApi(tempConfig);

    const response = await tempAuthClient.authTokenRefreshCreate({
      tokenRefreshRequest: { refresh: refreshToken }
    });

    // 🔑 关键：根据后端实际响应格式处理
    // 如果后端返回统一格式 {code, message, data, timestamp}，需要提取data
    // 如果后端直接返回token数据，直接使用
    const tokenData = (response as any).data || response;
    if (tokenData?.access) {
      tokenManager.setToken(tokenData.access);
      return true;
    }
  } catch (error) {
    console.error('Token刷新失败:', error);
    // 刷新失败，清除所有token并跳转到登录页
    tokenManager.removeToken();
    tokenManager.setRefreshToken('');

    // 跳转到登录页面
    if (typeof window !== 'undefined') {
      window.location.href = '/login';
    }
    return false;
  }

  // 刷新失败，清除所有token
  tokenManager.removeToken();
  return false;
};

// API配置 - 使用全局配置
const createApiConfiguration = (): Configuration => {
  return new Configuration({
    basePath: API_CONFIG.basePath,  // 🔑 关键：使用全局配置
    middleware: [
      {
        pre: async (context) => {
          const url = context.url;

          // 只有非公开接口才添加认证头
          if (!isPublicEndpoint(url)) {
            const currentToken = tokenManager.getToken();
            if (currentToken && context.init.headers) {
              (context.init.headers as any)['Authorization'] = `Bearer ${currentToken}`;
            }
          }

          return Promise.resolve(context);
        },
        post: async (context) => {
          const response = context.response;

          // 处理401未授权错误
          if (response.status === 401 && !isPublicEndpoint(context.url)) {
            const refreshed = await handleTokenRefresh();
            if (refreshed) {
              // 重新发送请求
              const newHeaders = { ...context.init.headers } as any;
              newHeaders['Authorization'] = `Bearer ${tokenManager.getToken()}`;

              return fetch(context.url, {
                ...context.init,
                headers: newHeaders,
              });
            } else {
              // 跳转到登录页
              window.location.href = '/login';
            }
          }

          return response;
        }
      }
    ]
  });
};

// 导出API客户端 - 按后端应用模块划分
export const apiClients = {
  // 🔑 关键：每个后端应用对应专门的API客户端类
  auth: new AuthApi(createApiConfiguration()),
  users: new UsersApi(createApiConfiguration()),
  permissions: new PermissionsApi(createApiConfiguration()),
  // ❌ 禁止使用通用的DefaultApi，必须按应用模块划分
};
